package com.cq.hd.order.factory;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.constant.OrderNoteConstant;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.NoUtils;
import com.cq.hd.member.api.TbAppUserApi;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.TbBusinessMerchantApi;
import com.cq.hd.member.api.vo.AppUserVo;
import com.cq.hd.member.api.vo.BusinessMerchantVo;
import com.cq.hd.member.api.vo.BusinessPointsMallProductVo;
import com.cq.hd.member.api.vo.BusinessPointsMallSettingsVo;
import com.cq.hd.order.api.dto.CreateOrderDto;
import com.cq.hd.order.api.dto.OrderCommissionDto;
import com.cq.hd.order.api.vo.CreateOrderVo;
import com.cq.hd.order.mapper.TbOrderItemMapper;
import com.cq.hd.order.mapper.TbOrderMapper;
import com.cq.hd.order.po.TbOrderItemPo;
import com.cq.hd.order.po.TbOrderPo;
import com.cq.hd.order.service.PftService;
import com.cq.hd.order.validator.ActiveOrderEnrollInfoValidator;
import com.cq.hd.order.service.TbOrderService;
import com.cq.hd.product.api.TbActiveApi;
import com.cq.hd.product.api.dto.ActiveEnrollInfoSonDto;
import com.cq.hd.product.api.dto.ActiveStepPriceSonDto;
import com.cq.hd.product.api.dto.ActiveSubStockDto;
import com.cq.hd.product.api.vo.ActiveRedPacketBillPageVo;
import com.cq.hd.product.api.vo.ActiveVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class EnrollOrderHandler extends AbstractOrderHandler {

    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private TbOrderService orderService;

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Autowired
    private TbBusinessMerchantApi businessMerchantApi;

    @Autowired
    private TbActiveApi activeApi;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private PftService pftService;

    @Autowired
    private TbAppUserApi appUserApi;

    @Autowired
    private TbBusinessApi businessApi;

    @Override
    protected Integer getType() {
        return ActiveTypeEnum.ENROLL.getValue();
    }

    @Override
    public CreateOrderVo createOrder(CreateOrderDto createOrderDto, ActiveVo activeVo) {
        String code = createOrderDto.getCode();
        Long redPacketBillId = createOrderDto.getRedPacketBillId();
        Integer orderNum = createOrderDto.getOrderNum();
        Long userId = createOrderDto.getUserId();
        Long activeId = createOrderDto.getActiveId();

        // 是否是零元购活动（1-不是，2-是）
        Integer zeroState = activeVo.getZeroState();
        // 阶梯价格列表(报名)
        List<ActiveStepPriceSonDto> activeStepPrices = activeVo.getActiveStepPrices();
        // 报名信息列表(报名)
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeVo.getActiveEnrollInfos();

        Long businessId = activeVo.getBusinessId();
        // 活动价格
        BigDecimal activePrice = activeVo.getActivePrice();
        // 活动限制的报名人数
//        Integer enrollNum = activeVo.getEnrollNum();

        LocalDateTime now = LocalDateTime.now();
        Integer activeState = activeVo.getActiveState();
        LocalDateTime startTime = activeVo.getStartTime();
        LocalDateTime endTime = activeVo.getEndTime();
        if (startTime.compareTo(now) > 0) {
            activeState = ActiveStateEnum.NO_START.getValue();
        } else if (endTime.compareTo(now) <= 0) {
            activeState = ActiveStateEnum.ENDED.getValue();
        } else if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
            activeState = ActiveStateEnum.IN_PROGRESS.getValue();
        }

        if (ActiveStateEnum.ENDED.getValue().equals(activeState)) {
            Throw.isBusinessException("活动已结束");
        }

        if (ActiveStateEnum.NO_START.getValue().equals(activeState)) {
            Throw.isBusinessException("活动未开始");
        }

        // 判断活动的库存是否充足
        Integer remainStock = activeVo.getRemainStock();
        if (remainStock - orderNum < 0) {
            Throw.isBusinessException("活动库存不足");
        }

        // 现在纯报名活动也要有活动价，所以不再取阶梯价最大值
        // 如果是阶梯价格，则取最大的价格作为活动价格，最后都核销完之后再返还金额
        Integer stepPriceState = activeVo.getStepPriceState();
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            // 根据活动id查询阶梯价格数据
            if (!CollectionUtils.isEmpty(activeStepPrices)) {
                // 倒序阶梯价格，获取阶梯最大价格
                activeStepPrices = activeStepPrices.stream()
                        .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollPrice).reversed())
                        .collect(Collectors.toList());
                BigDecimal maxStepPrice = activeStepPrices.get(0).getEnrollPrice();
                // 兼容旧版activePrice为空的情况
                if (maxStepPrice.compareTo(activePrice) > 0) {
                    activePrice = maxStepPrice;
                }
            }
        }

        // 报名次数限制(同个用户最多可报名几次)
        Integer totalOrderCount = orderService.userActiveOrderCount(userId, activeId);
        Integer limitEnrollNum = activeVo.getLimitEnrollNum();
        if (limitEnrollNum != null) {
            // 查询下单用户的待支付，待核销、核销中、已核销、已完成的该活动的订单数
            int canOrderNum = limitEnrollNum - totalOrderCount;
            if (orderNum > canOrderNum) {
                Throw.isBusinessException("超过报名次数");
            }
        }

        // 校验报名信息
        ActiveOrderEnrollInfoValidator.validate(createOrderDto, activeVo);

        List<com.cq.hd.order.api.dto.ActiveEnrollInfoSonDto> getActiveEnrollInfos = createOrderDto.getActiveEnrollInfos();
        // 订单总额=活动价格*下单数量
        BigDecimal orderPrice = activePrice.multiply(new BigDecimal(String.valueOf(orderNum)));

        // 校验红包数据
        ActiveRedPacketBillPageVo activeRedPacketBillPageVo = getRedPacketBill(redPacketBillId, userId, activeId, totalOrderCount, orderPrice);
        BigDecimal redPacketAmt = BigDecimal.ZERO;
        if (activeRedPacketBillPageVo != null) {
            redPacketAmt = activeRedPacketBillPageVo.getAmt();
        }

        // 商家是否有开启积分商城，有的话，用户下单可以拿积分，经纪人分销可以拿积分
        BusinessPointsMallSettingsVo pointsMallSettingsVo = getPointsMallSettings(businessId);
        BigDecimal distributionPointsRate = pointsMallSettingsVo.getDistribution(); // 分销活动，每获得1元佣金，奖励x积分
        BigDecimal consumePointsRate = pointsMallSettingsVo.getConsume(); // 每消费1元，奖励x积分

        // 优惠金额（打折优惠=订单总额-订单总额*折扣）
        BigDecimal discountAmt = BigDecimal.ZERO;
        // 实付金额=订单总额-红包金额-优惠金额
        BigDecimal payPrice = orderPrice.subtract(redPacketAmt).subtract(discountAmt);

        // 需要查询code是否有效，获取经纪人id和推广经济类型
        OrderCommissionDto orderCommissionDto = new OrderCommissionDto();
        orderCommissionDto.setCode(code);
        orderCommissionDto.setUserId(userId);
        orderCommissionDto.setOrderPrice(orderPrice);
        orderCommissionDto.setPayPrice(payPrice);
        orderCommissionDto.setOrderNum(orderNum);
        orderCommissionDto = calOrderCommission(orderCommissionDto, activeVo, distributionPointsRate);

        // 实际全核销佣金金额=活动价格*佣金比例=固定佣金金额*下单数量
        BigDecimal actualCommissionAmt = orderCommissionDto.getActualCommissionAmt();
        // 计算佣金类型(0-无,1-固定佣金,2-固定佣金比例，3-专属佣金比例)
        Integer calCommissionType = orderCommissionDto.getCalCommissionType();
        // 商家跟一级经纪人专属佣金比例
        BigDecimal exclusiveCommissionRate = orderCommissionDto.getExclusiveCommissionRate();
        // 二级经纪人可得的佣金比例
        BigDecimal subAgentCommissionRate = orderCommissionDto.getSubAgentCommissionRate();
        // 二级经纪人可得佣金
        BigDecimal subAgentCommissionAmt = orderCommissionDto.getSubAgentCommissionAmt();
        String otherEquity = orderCommissionDto.getOtherEquity();
        Long agentId = orderCommissionDto.getAgent1Id(); // 一级经纪人id
        Long agent2Id = orderCommissionDto.getAgent2Id(); // 二级经纪人id
        // 下单用户可得积分
        BigDecimal userPointsAmt = payPrice.multiply(consumePointsRate);
        // 一级经纪人可得积分
        BigDecimal agentPointsAmt = orderCommissionDto.getAgentPointsAmt();
        // 二级经纪人可得积分
        BigDecimal subAgentPointsAmt = orderCommissionDto.getSubAgentPointsAmt();
        // 积分结算状态：0无需结算 1待结算 2已结算
        int pointsSettleState = 0;
        if (userPointsAmt.compareTo(BigDecimal.ZERO) > 0 || agentPointsAmt.compareTo(BigDecimal.ZERO) > 0|| subAgentPointsAmt.compareTo(BigDecimal.ZERO) > 0) {
            pointsSettleState = 1;
        }

        // 查询商家数据，获取商家自有商户id
        BusinessMerchantVo businessMerchantVo = businessMerchantApi.getOwnByBusinessId(businessId, OwnStateEnum.YES.getValue()).unpack();
        Long merchantId = businessMerchantVo.getMerchantId();

        // 查询再邀x人，可返x元
        String inviteReturnMsg = "";
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            if (!CollectionUtils.isEmpty(activeStepPrices)) {
                // 当前报名活动已经报名成功的用户数
                int enrolledNum = 0;

                // 根据活动id查询阶梯价格数据
                List<TbOrderItemPo> activeEnrollOrderItemPos = orderItemMapper.selectList(new QueryWrapper<TbOrderItemPo>().eq("del_state", 0)
                        .eq("active_id", activeId));
                if (!CollectionUtils.isEmpty(activeEnrollOrderItemPos)) {
                    // 过滤符合报名条件的用户（只要在活动结束前没取消的都算，活动结束后取消也算）
                    for (TbOrderItemPo orderItemPo : activeEnrollOrderItemPos) {
                        // 如果用户取消参与活动，且活动结束时间不早于取消活动时间，则不计入报名用户数
                        if (SubOrderStateEnum.CANCEL.getValue().equals(orderItemPo.getSubOrderState())
                                && endTime.compareTo(orderItemPo.getCancelTime()) >= 0) {
                            continue;
                        }

                        enrolledNum += 1;
                    }
                    // 当前总报名用户数=已报名用户+当前下单人数
                    enrolledNum += orderNum;
                }

                // 根据阶梯报名人数正序
                activeStepPrices = activeStepPrices.stream()
                        .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollNum))
                        .collect(Collectors.toList());

                ActiveStepPriceSonDto activeStepPrice = activeStepPrices.get(0);
                Integer firstEnrollNum = activeStepPrice.getEnrollNum();
                if (enrolledNum < firstEnrollNum) {
                    // 报名成功，未满第一档人数，支付完成后提示：还差x人即可开启活动
                    inviteReturnMsg = String.format("还差%s人即可开启活动", firstEnrollNum - enrolledNum);
                } else {
                    // 报名成功，满第一档人数，支付完成后提示：再邀x人，可返y元（对比第二档人数，逐级判断）

                    // 再邀x人
                    int inviteNum = 0;
                    // 可返x元
                    BigDecimal returnAmt = BigDecimal.ZERO;
                    for (ActiveStepPriceSonDto activeStepPriceSonDto : activeStepPrices) {
                        Integer enrollNum = activeStepPriceSonDto.getEnrollNum();
                        BigDecimal enrollPrice = activeStepPrice.getEnrollPrice();

                        // 取下一阶级的报名人数对比，如果都没匹配上，则表示已满员
                        if (enrolledNum < enrollNum) {
                            // 计算再邀人数=下一阶级报名人数-已报名人数
                            inviteNum = enrollNum - enrolledNum;
                            // 计算可返金额=当前报名价格-对应阶级报名价格
                            returnAmt = activePrice.subtract(enrollPrice);
                            break;
                        }
                    }

                    if (inviteNum != 0 && returnAmt.compareTo(BigDecimal.ZERO) > 0) {
                        inviteReturnMsg = String.format("再邀%s人，可返%s元", inviteNum, returnAmt);
                    }
                }
            }
        }

        // 生成订单号
        String orderNo = NoUtils.getActiveOrderNo();
        Long orderId = 0L;
        AppUserVo appUserVo = appUserApi.getById(userId).unpack();
        List<TbOrderItemPo> tbOrderItemPos = new ArrayList<>();

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 创建订单数据
            TbOrderPo tbOrderPo = new TbOrderPo();
            tbOrderPo.setSignInRequired(SignInStatusEnum.NEED.getValue());
            tbOrderPo.setBusinessId(activeVo.getBusinessId());
            tbOrderPo.setActiveId(activeId);
            tbOrderPo.setAgentId(agentId);
            tbOrderPo.setAgent2Id(agent2Id);
            tbOrderPo.setUserId(userId);
            tbOrderPo.setActiveShareCode(code);
            tbOrderPo.setOrderNo(orderNo);
            tbOrderPo.setOrderType(getType());
            tbOrderPo.setMerchantId(merchantId);
            tbOrderPo.setActiveTitle(activeVo.getActiveTitle());
            tbOrderPo.setActiveImg(activeVo.getActiveImg());
            tbOrderPo.setStartTime(activeVo.getStartTime());
            tbOrderPo.setEndTime(activeVo.getEndTime());
            tbOrderPo.setValidStartTime(activeVo.getValidStartTime());
            tbOrderPo.setValidEndTime(activeVo.getValidEndTime());
            tbOrderPo.setSubsidyState(activeVo.getSubsidyState());
            tbOrderPo.setDiscountState(activeVo.getDiscountState());
            tbOrderPo.setStepPriceState(activeVo.getStepPriceState());
            tbOrderPo.setAgentState(activeVo.getAgentState());
            tbOrderPo.setVerifyMethod(activeVo.getVerifyMethod());
            tbOrderPo.setNoFullAutoRefundState(activeVo.getNoFullAutoRefundState());
            tbOrderPo.setTotalStock(activeVo.getTotalStock());
            if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
                // 如果活动需要审核，则状态为待审核状态，需要在商家后台审核
                if (activeVo.getAuditRequired() != null && activeVo.getAuditRequired() == 1) {
                    tbOrderPo.setOrderState(OrderStateEnum.WAIT_AUDIT.getValue());
                    tbOrderPo.setOrderNote(OrderNoteConstant.EIGHT);
                } else {
                    tbOrderPo.setOrderState(OrderStateEnum.WAIT_VERIFY.getValue());
                    tbOrderPo.setPayTime(now);
                }
            } else {
                tbOrderPo.setOrderState(OrderStateEnum.WAIT_PAY.getValue());
            }
            tbOrderPo.setZeroState(zeroState);
            tbOrderPo.setOrderNum(orderNum);
            tbOrderPo.setActivePrice(activePrice);
            tbOrderPo.setOrderPrice(orderPrice);
            tbOrderPo.setPayPrice(payPrice);
            tbOrderPo.setRedPacketBillId(redPacketBillId);
            tbOrderPo.setRedPacketAmt(redPacketAmt);
            tbOrderPo.setDiscountAmt(discountAmt);
            tbOrderPo.setCommissionAmt(activeVo.getCommissionAmt());
            tbOrderPo.setCommissionRate(activeVo.getCommissionRate());
            tbOrderPo.setOtherEquity(otherEquity);
            tbOrderPo.setExclusiveCommissionRate(exclusiveCommissionRate);
            tbOrderPo.setSubAgentCommissionRate(subAgentCommissionRate);
            tbOrderPo.setSubAgentCommissionAmt(subAgentCommissionAmt);
            tbOrderPo.setCalCommissionType(calCommissionType);
            tbOrderPo.setActualCommissionAmt(actualCommissionAmt);
            tbOrderPo.setUserPointsAmt(userPointsAmt);
            tbOrderPo.setAgentPointsAmt(agentPointsAmt);
            tbOrderPo.setSubAgentPointsAmt(subAgentPointsAmt);
            tbOrderPo.setOrderTime(now);
            tbOrderPo.setCreateTime(now);
            tbOrderPo.setUpdateTime(now);
            int insert = orderMapper.insert(tbOrderPo);
            if (insert == 0) {
                Throw.isBusinessException("下单失败");
            }
            orderId = tbOrderPo.getId();

            // 生成核销码
            String verifyCode;

            for (int i = 0; i < orderNum; i++) {
                BigDecimal merchantAmt = BigDecimal.ZERO;
                BigDecimal subtract = payPrice.subtract(actualCommissionAmt);
                if (subtract.compareTo(BigDecimal.ZERO) > 0) {
                    if (orderPrice.compareTo(BigDecimal.ZERO) > 0) {
                        // 计算商户订单本金=商品价格/商品总价 * (实付金额-佣金)
                        merchantAmt = activePrice.multiply(payPrice.subtract(actualCommissionAmt)).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
                    } else {
                        merchantAmt = BigDecimal.ZERO;
                    }
                }

                // 报名订单不补贴（佣金和红包）
                // 计算总补贴=商品价格-本金
//                BigDecimal totalSubsidyAmt = activePrice.subtract(merchantAmt);
                BigDecimal totalSubsidyAmt = BigDecimal.ZERO;

                BigDecimal orderItemRedPacketAmt = BigDecimal.ZERO;
                BigDecimal commissionAmt = BigDecimal.ZERO;
                BigDecimal subCommissionAmt = BigDecimal.ZERO;
                BigDecimal distributionOrderAmt = BigDecimal.ZERO;
                BigDecimal orderItemUserPointsAmt = BigDecimal.ZERO; // 子订单用户可得积分
                BigDecimal orderItemAgentPointsAmt = BigDecimal.ZERO; // 子订单一级经纪人可得积分
                BigDecimal orderItemSubAgentPointsAmt = BigDecimal.ZERO; // 子订单二级经纪人可得积分
                if (orderPrice.compareTo(BigDecimal.ZERO) > 0) {
                    // 计算红包=商品价格/商品总价 * 红包金额
                    orderItemRedPacketAmt = activePrice.multiply(redPacketAmt).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
                    // 计算佣金=商品价格/商品总价 * 实付金额 * 佣金比例=商品价格/商品总价 * 佣金（全核销）
                    commissionAmt = activePrice.multiply(actualCommissionAmt).divide(orderPrice, 2, BigDecimal.ROUND_DOWN);
                    // 二级经纪人可得佣金
                    subCommissionAmt = commissionAmt.multiply(subAgentCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                    // 计算分销金额=商品价格/商品总价 * 实付金额
                    distributionOrderAmt = activePrice.multiply(payPrice).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
                    orderItemUserPointsAmt = activePrice.multiply(userPointsAmt).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
                    orderItemAgentPointsAmt = activePrice.multiply(agentPointsAmt).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
                    orderItemSubAgentPointsAmt = activePrice.multiply(subAgentPointsAmt).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
                }

                // 计算商户订单补贴(该订单商场补贴的金额)=总补贴-红包
                BigDecimal merchantSubsidyAmt = BigDecimal.ZERO;
                if (totalSubsidyAmt.compareTo(BigDecimal.ZERO) > 0) {
                    merchantSubsidyAmt = totalSubsidyAmt.subtract(orderItemRedPacketAmt);
                }

                // 生成子订单号
                String subOrderNo = NoUtils.getActiveSubOrderNo();

                while (true) {
                    verifyCode = NoUtils.getVerifyCode();
                    Integer verifyCodeCount = orderItemMapper.selectCount(new QueryWrapper<TbOrderItemPo>().eq("verify_code", verifyCode));
                    if (verifyCodeCount == null || verifyCodeCount <= 0) {
                        break;
                    }
                }

                TbOrderItemPo tbOrderItemPo = new TbOrderItemPo();
                tbOrderItemPo.setItemGroup(i + 1); // 子单分组
                tbOrderItemPo.setBusinessId(businessId);
                tbOrderItemPo.setActiveId(activeId);
                tbOrderItemPo.setAgentId(agentId);
                tbOrderItemPo.setAgent2Id(agent2Id);
                tbOrderItemPo.setOrderId(orderId);
                tbOrderItemPo.setUserId(userId);
                tbOrderItemPo.setSubOrderNo(subOrderNo);
                tbOrderItemPo.setOrderType(getType());
                // 报名订单所属商户，哪个商家发起的，就关联哪个商家自有商户
                tbOrderItemPo.setMerchantId(merchantId);
                tbOrderItemPo.setGoodsId("");
                tbOrderItemPo.setGoodsName(activeVo.getActiveTitle());
                tbOrderItemPo.setGoodsImgs(activeVo.getActiveImg());
                tbOrderItemPo.setGoodsPrice(activePrice);
                tbOrderItemPo.setGoodsNum(1);
                tbOrderItemPo.setVerifyCode(verifyCode);
                tbOrderItemPo.setMerchantAmt(merchantAmt);
                tbOrderItemPo.setMerchantSubsidyAmt(merchantSubsidyAmt);
                tbOrderItemPo.setCommissionAmt(commissionAmt);
                tbOrderItemPo.setSubAgentCommissionAmt(subCommissionAmt);
                tbOrderItemPo.setRedPacketAmt(orderItemRedPacketAmt);
                tbOrderItemPo.setTotalSubsidyAmt(totalSubsidyAmt);
                tbOrderItemPo.setDistributionOrderAmt(distributionOrderAmt);
                tbOrderItemPo.setReturnAmt(BigDecimal.ZERO);

                // 零元购
                if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
                    // 如果活动需要审核，则状态为待审核状态，需要在商家后台审核
                    if (activeVo.getAuditRequired() != null && activeVo.getAuditRequired() == 1) {
                        tbOrderItemPo.setSubOrderState(SubOrderStateEnum.WAIT_AUDIT.getValue());
                    } else {
                        tbOrderItemPo.setSubOrderState(SubOrderStateEnum.WAIT_VERIFY.getValue());
                    }
                } else {
                    tbOrderItemPo.setSubOrderState(SubOrderStateEnum.WAIT_PAY.getValue());
                }
                tbOrderItemPo.setZeroState(zeroState);
                tbOrderItemPo.setSettleState(SettleStateEnum.NO.getValue());
                tbOrderItemPo.setOrderTime(tbOrderPo.getOrderTime());
                tbOrderItemPo.setExpireTime(activeVo.getValidEndTime());
                tbOrderItemPo.setEnrollInfo(CollectionUtils.isEmpty(getActiveEnrollInfos) ? "" : JSON.toJSONString(getActiveEnrollInfos));
                tbOrderItemPo.setCreateTime(now);
                tbOrderItemPo.setUpdateTime(now);
                tbOrderItemPo.setUserPointsAmt(orderItemUserPointsAmt);
                tbOrderItemPo.setAgentPointsAmt(orderItemAgentPointsAmt);
                tbOrderItemPo.setSubAgentPointsAmt(orderItemSubAgentPointsAmt);
                tbOrderItemPo.setPointsSettleState(pointsSettleState);

                tbOrderItemPo.setVerifyType(activeVo.getVerifyType());
                tbOrderItemPo.setPftSupplier(activeVo.getPftSupplier());
                tbOrderItemPo.setPftProduct(activeVo.getPftProduct());
                tbOrderItemPo.setPftTicket(activeVo.getPftTicket());

                // 子订单类型
                tbOrderItemPo.setItemType(OrderItemTypeEnum.SIGN_IN.getValue());

                if (VerifyTypeEnum.TYF.getValue().equals(tbOrderItemPo.getVerifyType())) {
                    boolean flag = pftService.orderPreCheck(tbOrderItemPo, appUserVo);
                    if (!flag) {
                        Throw.isBusinessException("票付通下单失败");
                    }
                }

                insert = orderItemMapper.insert(tbOrderItemPo);
                if (insert == 0) {
                    Throw.isBusinessException("下单失败");
                }

                tbOrderItemPos.add(tbOrderItemPo);
            }

            // 扣减活动库存，用户报名活动信息
            ActiveSubStockDto activeSubStockDto = new ActiveSubStockDto();
            activeSubStockDto.setActiveId(activeId);
            activeSubStockDto.setNum(orderNum);
            activeSubStockDto.setActiveRedPacketBillPageVo(activeRedPacketBillPageVo);
            boolean subResult = activeApi.subActiveStock(activeSubStockDto).unpack();
            if (!subResult) {
                Throw.isBusinessException("活动库存不足");
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<创建报名活动订单>事务异常回滚", e);
            Throw.isBusinessException(e.getMessage());
        }

        // 校验子订单佣金累加是否等于全核销佣金
        if (actualCommissionAmt != null && actualCommissionAmt.compareTo(BigDecimal.ZERO) > 0 && !CollectionUtils.isEmpty(tbOrderItemPos)) {
            // 累计子订单佣金
            BigDecimal sonTotalCommissionAmt = tbOrderItemPos.stream()
                    .map(TbOrderItemPo::getCommissionAmt)
                    .filter(commissionAmt -> commissionAmt != null && commissionAmt.compareTo(BigDecimal.ZERO) > 0)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            if (sonTotalCommissionAmt.compareTo(actualCommissionAmt) < 0) {
                TbOrderItemPo tbOrderItemPo = tbOrderItemPos.get(tbOrderItemPos.size() - 1);
                BigDecimal amt = tbOrderItemPo.getCommissionAmt().add(actualCommissionAmt.subtract(sonTotalCommissionAmt));
                BigDecimal subAmt = amt.multiply(subAgentCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                tbOrderItemPo.setCommissionAmt(amt);
                tbOrderItemPo.setSubAgentCommissionAmt(subAmt);
                int update = orderItemMapper.updateById(tbOrderItemPo);
                if (update == 0) {
                    log.error("子订单佣金累加不等于全核销佣金，更新最后一个子订单的佣金失败，orderItemId：{}", tbOrderItemPo.getId());
                }
            }
        }

        CreateOrderVo createOrderVo = new CreateOrderVo();
        createOrderVo.setOrderId(orderId);
        createOrderVo.setOrderNo(orderNo);
        createOrderVo.setInviteReturnMsg(inviteReturnMsg);
        createOrderVo.setZeroState(zeroState);

        return createOrderVo;
    }

    @Override
    public CreateOrderVo createPointsOrder(CreateOrderDto createOrderDto, BusinessPointsMallProductVo productVo) {
        return null;
    }
}
